package com.skx.rrde.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;


    @RequestMapping(value = "/ribbon-consumer",method= RequestMethod.GET)
    public String helloConsumer (){
        String s = this.restTemplate.getForEntity("http://HELLOSERVICE/hellos", String.class).getBody();
        return s;
    }


    @RequestMapping(value = "/ribbon-consumer2",method= RequestMethod.GET)
    public String helloConsumer2 (){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("HELLO-SERVICE");
        return null;
    }

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/ribbon-consumer1",method= RequestMethod.GET)
    public String helloConsumer1 (){
        List<ServiceInstance> list = discoveryClient.getInstances("STORES");
        System.out.println("discoveryClient.getServices().size() = " + discoveryClient.getServices().size());
        for (String s : discoveryClient.getServices()) {
            System.out.println("services " + s);
            List<ServiceInstance> serviceInstances = discoveryClient.getInstances(s);
            for (ServiceInstance si : serviceInstances) {
                System.out.println("    services:" + s + ":getHost()=" + si.getHost());
                System.out.println("    services:" + s + ":getPort()=" + si.getPort());
                System.out.println("    services:" + s + ":getServiceId()=" + si.getServiceId());
                System.out.println("    services:" + s + ":getUri()=" + si.getUri());
                System.out.println("    services:" + s + ":getMetadata()=" + si.getMetadata());
            }
        }
        System.out.println(list.size());
        if (list != null && list.size() > 0) {
            System.out.println(list.get(0).getUri());
        }
        return null;
    }

}
